import React, { useMemo } from 'react'
import { Tag, Space } from 'antd'
import { useT, CreateExecutor } from '@designable/event-system'
import { useForm } from '@formily/react'
import { observer } from '@formily/reactive-react'

// 安全执行表达式的工具函数
const safeExecute = (executor: any, context: any, fallback: any = null) => {
  try {
    if (!executor) return fallback
    return CreateExecutor(executor)(context)
  } catch (error) {
    console.error('执行表达式失败:', error)
    return fallback
  }
}

export const DetailHeader: React.FC<{
  title: string
  style?: React.CSSProperties
  children?: React.ReactNode
  titleKey: string
  statusKey: string
  statusNameKey: string
  statusColorExpression: string
}> = observer((props) => {
  const {
    title,
    titleKey,
    statusKey,
    statusNameKey,
    style,
    children,
    statusColorExpression,
  } = props
  const $t = useT()
  const form = useForm()
  const formValues = form.getFormState().values

  // 从表单中获取 orderNo 值作为标题
  const titleValue = formValues[titleKey] || title
  const status = formValues[statusKey] || '1'
  const statusName = formValues[statusNameKey] || '状态'

  // 执行状态颜色表达式
  const tagColor = useMemo(() => {
    if (statusColorExpression) {
      const color = safeExecute(statusColorExpression, {})
      return color
    }
    return {}
  }, [statusColorExpression, status])
  const color = tagColor[status]

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        ...style,
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'flex-start',
          fontSize: 20,
          marginBottom: 20,
        }}
      >
        <span style={{ fontWeight: 'bold' }}>
          {$t(title)}：{titleValue}
        </span>
        <div style={{ marginLeft: 10 }}>
          <Tag style={{ fontSize: 14 }} color={color}>
            {statusName}
          </Tag>
        </div>
      </div>
      <Space>{children}</Space>
    </div>
  )
})
